/**
 *
 */
package com.zhuoyue.elmt.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eit.eitsite.modules.sys.entity.Dict;
import com.eit.eitsite.modules.sys.service.SystemService;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.zhuoyue.elmt.entity.MaintenanceContractDevice;
import com.zhuoyue.elmt.entity.MaintenanceStaffDevice;
import com.zhuoyue.elmt.entity.WbMtGroupStaff;
import com.zhuoyue.elmt.service.MaintenanceContractDeviceService;
import com.zhuoyue.elmt.service.MaintenanceStaffDeviceService;
import com.zhuoyue.elmt.service.WbMtGroupStaffService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.common.utils.StringUtils;
import com.zhuoyue.elmt.entity.MaintenanceStaff;
import com.zhuoyue.elmt.service.MaintenanceStaffService;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 维保人员备案Controller
 *
 * @author chenhao
 * @version 2016-09-08
 */
@Controller
@RequestMapping(value = "${adminPath}/elmt/maintenanceStaff")
public class MaintenanceStaffController extends BaseController {

    @Autowired
    private MaintenanceStaffService maintenanceStaffService;

    @Autowired
    private MaintenanceStaffDeviceService maintenanceStaffDeviceService;

    @Autowired
    private MaintenanceContractDeviceService maintenanceContractDeviceService;

    @Autowired
    private WbMtGroupStaffService wbMtGroupStaffService;

    @ModelAttribute
    public MaintenanceStaff get(@RequestParam(required = false) String id) {
        MaintenanceStaff entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = maintenanceStaffService.get(id);
        }
        if (entity == null) {
            entity = new MaintenanceStaff();
        }
        return entity;
    }

    @RequiresPermissions("elmt:maintenanceStaff:view")
    @RequestMapping(value = {"list", ""})
    public String list(String sbzcdm, String parentId, MaintenanceStaff maintenanceStaff, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!UserUtils.getUser().isAdmin()) {
            maintenanceStaff.setMaintenanceUnitId(UserUtils.getUser().getCompany().getCode());
        }
        Page<MaintenanceStaff> page = maintenanceStaffService.findPage(new Page<MaintenanceStaff>(request, response), maintenanceStaff);
        if (StringUtils.isNotEmpty(sbzcdm)) {
            model.addAttribute("sbzcdm", sbzcdm);
        }
        if (StringUtils.isNotEmpty(parentId)) {
            model.addAttribute("parentId", parentId);
        }
        model.addAttribute("page", page);
        return "zhuoyue/elmt/maintenanceStaffList";
    }

    @RequiresPermissions("elmt:maintenanceStaff:view")
    @RequestMapping(value = "form")
    public String form(MaintenanceStaff maintenanceStaff, Model model) {
        model.addAttribute("maintenanceStaff", maintenanceStaff);
//        MaintenanceStaffDevice record = new MaintenanceStaffDevice();
        //        System.out.println("maintenanceStaff.getId()==========================" + maintenanceStaff.getId());
//        List<HashMap> list = new ArrayList();
//        if(maintenanceStaff.getId() != null) {
//            record.setMaintenanceStaff(maintenanceStaff.getId());
//            list = maintenanceStaffService.findStaffDeviceList(record);
//        }
//        model.addAttribute("list", list);
        return "zhuoyue/elmt/maintenanceStaffForm";
    }

    @RequiresPermissions("elmt:maintenanceStaff:edit")
    @RequestMapping(value = "save")
    public String save(MaintenanceStaff maintenanceStaff, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, maintenanceStaff)) {
            return form(maintenanceStaff, model);
        }
        if (!"true".equals(checkLoginName(maintenanceStaff.getOldLoginName(), maintenanceStaff.getLoginName()))){
            addMessage(model, "保存用户'" + maintenanceStaff.getLoginName() + "'失败，登录名已存在");
            return form(maintenanceStaff, model);
        }

        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(maintenanceStaff.getNewPassword())) {
            maintenanceStaff.setPasswd(SystemService.entryptPassword(maintenanceStaff.getNewPassword()));
        }

        // if(!UserUtils.getUser().isAdmin()){
        maintenanceStaff.setMaintenanceUnitId(UserUtils.getUser().getCompany().getCode());
        maintenanceStaff.setMaintenanceUnitName(UserUtils.getUser().getCompany().getName());

        if (StringUtils.isNotBlank(maintenanceStaff.getNewPassword())) {
            maintenanceStaff.setPasswd(SystemService.entryptPassword(maintenanceStaff.getNewPassword()));
        }

        // 时间
        Date curdate = new Date();
        if (StringUtils.isBlank(maintenanceStaff.getId())) {
            maintenanceStaff.setCreatedBy(UserUtils.getUser().getId());
            maintenanceStaff.setCreationDate(curdate);
        }
        maintenanceStaff.setLastUpdateBy(UserUtils.getUser().getId());
        maintenanceStaff.setLastUpdateDate(curdate);

        //        }
        maintenanceStaffService.save(maintenanceStaff);
        addMessage(redirectAttributes, "保存维保人员信息成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/maintenanceStaff/?repage";
    }

    @RequiresPermissions("elmt:maintenanceStaff:edit")
    @RequestMapping(value = "delete")
    public String delete(MaintenanceStaff maintenanceStaff, RedirectAttributes redirectAttributes) {
        maintenanceStaffService.delete(maintenanceStaff);
        addMessage(redirectAttributes, "删除维保人员信息成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/maintenanceStaff/?repage";
    }

    @RequiresPermissions("elmt:maintenanceStaff:edit")
    @RequestMapping(value = "selectStaffSave")
    public String selectStaffSave(String distribution, String contractNo, String parentId, Model model, RedirectAttributes redirectAttributes) {
        String[] contractNos = contractNo.split(",");
        MaintenanceStaffDevice maintenanceStaffDevice = null;
        MaintenanceContractDevice maintenanceContractDevice = null;
        for (int i = 0; i < contractNos.length; i++) {
            maintenanceContractDevice = new MaintenanceContractDevice();
            maintenanceContractDevice.setContractNo(contractNos[i]);
            List<MaintenanceContractDevice> list = maintenanceContractDeviceService.getByContractNo(maintenanceContractDevice);
            for (MaintenanceContractDevice contractDevice : list) {
                maintenanceStaffDevice = new MaintenanceStaffDevice();
                maintenanceStaffDevice.setDeviceCode(contractDevice.getDeviceCode());
                maintenanceStaffDevice.setMaintenanceStaff(distribution);
                maintenanceStaffDevice.setWbdwdm(UserUtils.getUser().getCompany().getCode());
                maintenanceStaffDeviceService.insert(maintenanceStaffDevice);
            }
        }
        redirectAttributes.addAttribute("parentId", parentId);
        model.addAttribute("closeWin", "0");
        model.addAttribute("message", "任务分配成功");
        return "zhuoyue/elmt/maintenanceStaffList";
    }

    @RequiresPermissions("elmt:maintenanceStaff:view")
    @RequestMapping(value = {"staffgroup"})
    public String staffgroup(String groupId, MaintenanceStaff maintenanceStaff, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!UserUtils.getUser().isAdmin()) {
            maintenanceStaff.setMaintenanceUnitId(UserUtils.getUser().getCompany().getCode());
        }
        HashMap qryMap = new HashMap();
        qryMap.put("groupId", groupId);

        Page<MaintenanceStaff> page = maintenanceStaffService.staffgrouppage(new Page<MaintenanceStaff>(request, response), maintenanceStaff);
        List<MaintenanceStaff> staffList = maintenanceStaffService.staffgroupnolist(qryMap);

        if (StringUtils.isNotEmpty(groupId)) {
            model.addAttribute("groupId", groupId);
        }

        model.addAttribute("page", page);
        model.addAttribute("staffList", staffList);

        return "zhuoyue/elmt/mainStaffGroup";
    }

    @RequiresPermissions("elmt:maintenanceStaff:edit")
    @RequestMapping(value = "staffgroupsave")
    public String staffgroupsave(String[] staffId, String groupId, String leader, Model model, RedirectAttributes redirectAttributes) {
        WbMtGroupStaff wbMtGroupStaff;
        List<WbMtGroupStaff> wbMtGroupStaffList = new ArrayList();
        for (int i = 0; i < staffId.length; i++) {
            wbMtGroupStaff = new WbMtGroupStaff();
            wbMtGroupStaff.setStaffId(staffId[i]);
            wbMtGroupStaff.setGroupId(groupId);
            wbMtGroupStaff.setLeader(leader);
            wbMtGroupStaffList.add(wbMtGroupStaff);

            wbMtGroupStaffService.save(wbMtGroupStaffList);

            //分配维保人员  如果是机构类型为“维保小组”，该字段显示为“维保组长”
            if(leader.equals("1")){
                HashMap map=new HashMap();
                map.put("staffId",staffId[i]);
                map.put("sysOfficeId",groupId);
                wbMtGroupStaffService.updateSysOfficePrimaryPerson(map);
            }
        }
        model.addAttribute("message", "维保人员分配成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/maintenanceStaff/staffgroup?groupId=" + groupId;
    }

    @RequiresPermissions("elmt:maintenanceStaff:edit")
    @RequestMapping(value = "staffgroupdelete")
    public String staffgroupdelete(WbMtGroupStaff wbMtGroupStaff, Model model, RedirectAttributes redirectAttributes) {
        wbMtGroupStaffService.deleterela(wbMtGroupStaff);
        model.addAttribute("message", "删除已分配维保人员成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/maintenanceStaff/staffgroup?groupId=" + wbMtGroupStaff.getGroupId();
    }

    @ResponseBody
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName !=null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName !=null && maintenanceStaffService.getByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }
}